<template>
  <div>
    <el-divider />
    <el-row>
      <el-col :span="12" :offset="6">
        <el-form ref="form" :model="userInfo" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model.trim="userInfo.username" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model.trim="userInfo.password" type="password" />
          </el-form-item>
          <el-form-item>
            <el-col :span="4">
              <el-button type="primary" @click="onSubmit">登录</el-button>
            </el-col>
            <el-button type="danger">
              <router-link to="/register">注册新用户</router-link>
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-divider />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref } from 'vue'
import { loginService } from '@/services/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userInfo = ref({ username: '', password: '' })


async function onSubmit() {
  const { username, password } = userInfo.value
  if (!username || !password) {
    ElMessage({ message: '用户名或密码错误不能为空', type: 'error', showClose: true })
    return
  }

  const responseModel = await loginService(username, password)
  console.log('login page==>responseModel\n', responseModel)
  if (!responseModel.ok) {
    ElMessage({ message: responseModel.message, type: 'error', showClose: true })
    return
  }
  alert('登录成功')
  window.sessionStorage.setItem('currentUserName', responseModel['data']['username']) //把当前登录的用户设置到session里
  await router.push('/')
}
</script>
